<template>
  <section>
    <el-col :span="24" class="toolbar">
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-plus" round @click="showAdd">添加文件</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-table :data="myFileList" border highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column header-align="center" align="center" type="selection" width="50"></el-table-column>
      <el-table-column header-align="center" prop="docName" label="文件名" min-width="120"></el-table-column>
      <el-table-column header-align="center" prop="createTime" label="创建日期" min-width="120"></el-table-column>
      <el-table-column header-align="center" label="操作" min-width="400">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-view" round type="info" @click="view(scope.row)">查看签名情况</el-button>
          <el-button size="mini" icon="el-icon-delete" round type="danger" @click="deleteit(scope.row)">删除</el-button>
          <el-button size="mini" icon="el-icon-edit-outline" round type="primary" @click="sign(scope.row)">签名
          </el-button>
          <el-button size="mini" icon="el-icon-message" round @click="send(scope.row)">发送</el-button>
          <el-button size="mini" icon="el-icon-sold-out" round @click="archived(scope.row)">归档</el-button>
          <el-button size="mini" icon="el-icon-download" round @click="downloadit(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length==0">批量删除</el-button>
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :page-sizes="pageSizes"
                     :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <el-dialog :title="formTitle" :visible.sync="visible" :close-on-modal="false">
      <el-form :model="fileForm" label-width="80px" :rules="formRules" ref="fileForm">
        <div v-if="!isupload">
          <el-form-item label="文件名" prop="docName">
            <el-input v-model="fileForm.docName" placeholder="请输入文件名" :disabled="this.activeName==='detail'"/>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" v-model="fileForm.remarks" :disabled="this.activeName==='detail'"/>
          </el-form-item>
        </div>
        <div v-if="isupload">
          <el-form-item label="上传文件" v-show="this.activeName==='add'">
            <el-upload ref="upload" class="upload-demo" drag action="/api/signDoc/add" :headers="headers"
                       :data="fileForm" :before-upload="beforeUpload" :auto-upload="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload_text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
            <el-button size="small" type="success" @click="submitUpload">上传</el-button>
          </el-form-item>
        </div>
        <el-form-item v-show="this.activeName==='add'">
          <el-button @click="isupload=!isupload">{{isupload?'上一步':'下一步'}}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-on:click="SaveSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="formTitle" :visible.sync="visible1" :close-on-modal="false">
      <el-form label-width="80px">
        <el-table :data="fileDetail" border highlight-current-row v-loading="listLoading" style="width: 100%;">
          <el-table-column header-align="center" prop="requestedId" label="被请求者" min-width="120"></el-table-column>
          <el-table-column header-align="center" align="center" label="状态" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.isSign===1">已签名</span>
              <span v-else-if="scope.row.isSign===-1">未签名</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>

    <el-dialog :title="formTitle" :visible.sync="visible2" :close-on-click-modal="false">
      <el-form  label-width="80px">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="姓名" style="width:200px;" clearable></el-input>
          <el-button type="primary" v-on:click="search" icon="el-icon-search" style="margin-left: 15px;">查询
          </el-button>
        </el-form-item>
        <el-table
          ref="singleTable"
          :data="userlist"
          highlight-current-row
          @current-change="selected"
          style="width: 500px;margin-left: 50px">
          <el-table-column
            type="index"
            width="80">
          </el-table-column>
          <el-table-column
            property="realName"
            label="姓名"
            width="210">
          </el-table-column>
          <el-table-column
            property="mobilePhone"
            label="手机号码"
            width="210">
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px;margin-left: 80px">
          <el-button @click="setCurrent()">取消选择</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native=" visible2= false">取消</el-button>
        <el-button type="primary" v-on:click="suresend" :loading="submitLoading">确定发送</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
  import {getNowTime} from "../../utils";
  import API from '@/api'

  export default {
    name: "my-files",
    data() {
      return {
        selectedid:'',
        currentRow:null,
        filters:{
          keyword:'',
        },
        userlist: [],
        totalCount: 0,
        fileDetail: [],
        fileimfor: {},
        sels: [],  //选中的数据数组
        myFileList: [],
        listLoading: false,
        user: {},
        activeName: "add", //add-添加，edit-编辑，detail-查看

        isupload: false,
        headers: {
          token: this.$cookie.get('token')
        },
        formTitle: "",
        fileForm: {},
        fileFormInit: {
          docName: "",
          remarks: "", //备注
          creatorId: '', //创建者
          holderId: '',  //持有者
          state: "1", //状态
          url: ""
        },
        formRules: {},
        visible: false,
        visible1: false,
        visible2: false,
        submitLoading: false,

        //分页参数
        pageSizes: this.CONSTANT.PAGE_SIZES,
        pageSize: this.CONSTANT.PAGE_SIZE,
        total: 0,
        pageIndex: 1, //页码
      }
    },
    methods: {
      selsChange(sels) {
        this.sels = sels;
      },
      init(data) {
        // this.listLoading = true;
        // this.myFileList = data;
        // console.log(this.myFileList);
        // this.listLoading = false;
      },
      beforeUpload(file) {
        this.fileForm.creatorId = this.user.id;
      },
      handleSizeChange(value) {
        this.pageSize = value;
        this.getFileList();
      },
      handleCurrentChange(value) {
        this.pageIndex = value;
        this.getFileList();
      },
      showAdd() {
        this.formTitle = "添加";
        this.activeName = 'add';
        this.fileForm = Object.assign({}, this.fileFormInit);
        this.visible = true;
      },
      submitUpload() {
        this.$refs.upload.submit();
      },
      getUserInfo() {
        API.user.info().then(res => {
          this.user = res.data.user;
          this.getFileList();
        }).catch(error => {
          console.log(error);
        });
      },
      getFileList() {
        let params = {
          page: this.pageIndex,
          limit: this.pageSize,
          creatorId: this.user.id,
        };
        API.signDoc.list(params).then(res => {
          if (!res.data.code) {
            this.myFileList = res.data.page.list;
            this.total = res.data.page.totalCount;
            let i = 0;
            for (i = 0; i < this.total; i++) {
              var date = new Date(this.myFileList[i].createTime);
              let d = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
              this.myFileList[i].createTime = d;
            }
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },
      sign(value) {
        this.$router.push({path: '/signPDF', query: {fileimfor: value}});
      },
      send(value) {
        console.log(value);
        this.formTitle='发送';
        this.visible2=true;
        let params = {
          limit:this.pageSize,
          page:this.pageIndex,
        };
        API.user.list(params).then(res=>{
          if(!res.data.code){
            this.userlist = res.data.page.list;
          }else {
            this.$message.error(res.data.msg);
          }
          this.listLoading = false;
        }).catch(error=>{
          console.log(error);
          this.$message.error(error);
          this.listLoading = false;
        });
      },
      search(){
        let para = {
          keyword: this.filters.keyword,
        };
        API.user.list(para).then(res=>{
          if(!res.data.code){
            this.userlist = res.data.page.list;
          }else {
            this.$message.error(res.data.msg);
          }
          this.listLoading = false;
        }).catch(error=>{
          console.log(error);
          this.$message.error(error);
          this.listLoading = false;
        });
      },
      selected(val) {
        this.currentRow = val;
      },
      setCurrent(row) {
        this.$refs.singleTable.setCurrentRow(row);
      },
      suresend(){
        console.log(this.selectedid);
      },
      view(value) {
        this.formTitle = "文件签名详情";
        let param = {
          signdocid: value.id,
        };
        API.signerq.list(param).then(res => {
          console.log(res);
          if (!res.data.code) {
            this.fileDetail = res.data.page.list;
            this.totalCount = res.data.page.totalCount;
            this.getRequested();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },
      getRequested: function () {
        for (let i = 0; i < this.totalCount; i++) {
          let id = this.fileDetail[i].requestedId;
          API.user.FindByid(id).then(res => {
            if (!res.data.code) {
              this.fileDetail[i].requestedId = res.data.user.realName;
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(error => {
            console.log(error);
            this.$message.error(error);
          })
        }
        this.visible1 = true;
      },
      batchRemove() {
        this.$confirm('此操作将永久删除这些文件，是否继续', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.idList = this.sels.map(item => item.id).toString().split(",");
          console.log(this.idList);
          API.signDoc.remove(this.idList).then((res) => {
            console.log(res.data.code);
            if (!res.data.code) {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.getFileList();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(error => {
            console.error(error);
          })
        })
      },
      deleteit(value) {
        this.$confirm('此操作将永久删除这些文件，是否继续', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.idList = value.id.toString().split(",");
          API.signDoc.remove(this.idList).then((res) => {
            console.log(res.data.code);
            if (!res.data.code) {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.getFileList();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(error => {
            console.error(error);
          })
        })
      },
      archived(value) {

      },
      downloadit(value) {

      },
      SaveSubmit: function () {
        this.$confirm('确认提交吗？', '提示', {}).then(() => {
          this.submitLoading = true;
          this.visible = false;
          this.submitLoading = false;
          this.getFileList(); //重新加载数据
        });
      }
    },
    activated() {
      this.getUserInfo();
    },
  }
</script>

<style scoped>

</style>
